// pages/exam/examGoing/examGoing.js
var app = getApp();
var config = require('../../../config.js');

//4种类型的题 //增加一种 不定项选择题 最少选择一个答案即可
var singleQList = null;
var multQList = null;
var booleanQList = null;
var inputQList = null;
var unsurenessQList = null;//value.unsurenessQuestions;//不定项

//当前答题的类型 0不定项选择题 1单选 2 多选 3判断 4填空 
var currentExamType = 1;
var currentList = null;
//当前题目在当前类型的集合种的position
var currentPosition = 0;
//当前题目在所有集合中的位置 
var currentExamInAllPosition = 1;

//记录分数

var exam_singlePoint = 0
var exam_multpoint = 0
var exam_booleanPoint = 0
var exam_inputPoint = 0
var exam_unsurenessPoint = 0

//记录用户选择的多选答案
var mult_answerList = [];

//考试结果实体 本地记录
var examResultInfo = {};
//分值 服务器返回的
var xzExamPaper = null;
var examDescInfo;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    currentExamType: 1,
    examType: "【单选题】",
    currentExamInfo: null,

    inputAnswerValue: null,
    currentanswerList: null,

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.resetData();
    this.initData(options);
    // 1 先进行不定项选择题
    this.setCurrentExamList();
    this.startNextQuestion();

    // app.globalData.bgMusic.stop();
    // app.globalData.bgMusicExam.play();

  },
  /**
 * 每次打开页面都会调用一次。
 */
  onShow: function () {
    // app.globalData.bgMusicExam.play();
  },
  onUnload: function () {
    // app.globalData.bgMusicExam.stop();
    // app.globalData.bgMusic.play();
  },

  //初始化考试题库
  initData: function (options) {
    var that = this;
    try {
      var value = wx.getStorageSync(config.examList); //取出缓存的问题信息
      if (value) {
        console.log('value====' + value)
        unsurenessQList = value.unsurenessQuestions;
        singleQList = value.singleQuestions;
        multQList = value.multipleQuestions;
        booleanQList = value.checkQuestions;
        inputQList = value.completionQuestions;
        xzExamPaper = value.xzExamPaper;
        examDescInfo = value.xzExam;
      
      }
    } catch (e) {
      console.log("初始化法律题库数据失败···");
    }



  },

  //重置所有数据
  resetData: function () {
    currentExamType = 0;
    currentList = null;
    currentPosition = 0;
    currentExamInAllPosition = 1;


    exam_singlePoint = 0
    exam_multpoint = 0
    exam_booleanPoint = 0
    exam_inputPoint = 0
    exam_unsurenessPoint = 0
    //考试结果实体
    examResultInfo = {};

    mult_answerList = []
  },


  //设置当前题库集合
  setCurrentExamList: function () {
    var that = this;
    if (currentExamType == 0) {
      //不定项选择题
      currentList = unsurenessQList;
    } else if (currentExamType == 1) {
      currentList = singleQList;
    } else if (currentExamType == 2) {
      currentList = multQList;
    } else if (currentExamType == 3) {
      currentList = booleanQList;
    }
    else {
      currentList = inputQList;
    }
  },

  //开始下一道题
  startNextQuestion: function () {
    var that = this;
    if (currentList && currentList.length > 0) {
      if (currentPosition < currentList.length) {
        //不是当前类型的最后一题
        var item = currentList[currentPosition];
        //设置data数据 刷新ui
        that.setData({
          currentExamInfo: item,
          currentanswerList: item.answers,
          currentExamInAllPosition: currentExamInAllPosition
        });
        currentPosition++;
        currentExamInAllPosition++;
      } else {
        //当前类型的所有的集合已经完成考试 开始下一类型

        if (currentExamType < 4) {
          currentPosition = 0;
          currentExamType++;
          setTimeout(function () {
            that.setData({
              currentExamType: currentExamType
            });
            //继续进行答题
            that.setCurrentExamList();
            that.showToast();
            that.startNextQuestion();
          }, 500);

        } else {
          //结束标记
          console.log("本轮答题结束啦啦啦啦啦-------------");
          that.startResult();
        }

      }

    } else {
      //
      that.showToast(false);
      if (currentExamType < 4) {
        currentPosition = 0;
        currentExamType++;
        setTimeout(function () {
          that.setData({
            currentExamType: currentExamType
          });
          //继续进行答题
          that.setCurrentExamList();
          that.showToast();
          that.startNextQuestion();
        }, 100);

      }
    }
  },

  //每次更换题型时 给用户提示
  showToast: function (isShow) {
    var that = this;
    var msg = '';
    var examType = "";
    if (currentExamType == 1) {
      msg = "下面是单选题";
      examType = "【单选题】";
    } else
      if (currentExamType == 2) {
        msg = "下面是多选题";
        examType = "【多选题】";
      } else if (currentExamType == 3) {
        msg = "下面是判断题";
        examType = "【判断题】";
      } else if (currentExamType == 4) {
        msg = "下面是填空题";
        examType = "【填空题】";
      }
    console.log("currentExamType==>" + currentExamType);
    console.log("isShow==>" + isShow);

    if (currentList && currentList.length > 0) {
      that.setData({
        examType: examType

      });
      wx.showToast({
        title: msg,
        icon: "none"
      })
    }




  },

  //填空题的输入监听
  inputAnswerListener(e) {
    this.setData({
      inputAnswerValue: e.detail.value
    })

  },

  //单选 多选 判断题的点击事件 + 不定项选择题
  onExamItemClick: function (event) {
    console.log("onExamItemClick（）执行啦 ");
    var that = this;
    //获取用户选择的答案
    var mSelectedId = event.currentTarget.dataset.answerid;
    var index = event.currentTarget.dataset.index;
    var examInfo = that.data.currentExamInfo;
    //根据index 取出当前点击的item对象
    var item = examInfo.answers[index];
    
    if (currentExamType == 2 || currentExamType == 0) {
      // 如果是多选  或者不定项选择
      if (item.isSelected) {
        item.isSelected = false;
        //从集合种移除已经存入的答案
        var list = that.removeAnswer(item);
        mult_answerList = list;
        that.setData({
          currentExamInfo: that.data.currentExamInfo,
          currentanswerList: examInfo.answers
        });
        return;
      }


      console.log("item.isSelected========" + item.isSelected);

      item.isSelected = true;
      that.setData({
        currentExamInfo: examInfo,
        currentanswerList: examInfo.answers
      });
      //存入集合中 计算分数使用
      if (!that.isHaveAnswered(item)) {
        mult_answerList.push(item);
      }

      console.log("mult_answerList length========" + mult_answerList.length);
    } else {

      if (item.isSelected) {
        item.isSelected = false;
        mult_answerList = [];
        that.setData({
          currentExamInfo: that.data.currentExamInfo,
          currentanswerList: examInfo.answers
        });


        return;
      }

      //获取用户选择的答案 
      if (mult_answerList.length == 0) {
        item.isSelected = true;
        that.setData({
          currentExamInfo: that.data.currentExamInfo,
          currentanswerList: examInfo.answers
        });

        //存入集合中 计算分数使用
        mult_answerList.push(item);
      } else {
        wx.showToast({
          title: '请您先取消答案',
          icon: 'none'
        })
        return;
      }

    }

  },

  //多选时 判断是否已经作答
  isHaveAnswered: function (obj) {
    if (mult_answerList) {
      for (var i = 0; i < mult_answerList.length; i++) {
        var item = mult_answerList[i];
        if (obj.id == item.id) {
          return true;
        }
      }
    }
    return false;

  },

  //移除答案
  removeAnswer: function (obj) {
    var list = [];
    if (mult_answerList) {
      for (var i = 0; i < mult_answerList.length; i++) {
        var item = mult_answerList[i];
        if (obj.id != item.id) {
          list.push(item);
        }
      }
    }

    return list;

  },

  //下一题 点击事件
  nextQuestion: function () {
    if (!xzExamPaper) {
      wx.showToast({
        title: '服务器错误！',
      })
      return;
    }

    var that = this;
    var examInfo = that.data.currentExamInfo;
    // 1 判断当前题目是否作答
    if (currentExamType == 4) {
      //填空题
      var inputAnswerValue = that.data.inputAnswerValue;
      console.log("用户输入答案为==" + inputAnswerValue);
      if (!inputAnswerValue) {
        wx.showToast({
          title: "您还没有作答！",
          icon: 'none'
        })
        return;
      } else {
        //判断答案 计算得分
        var ans = examInfo.answers;
        if (ans) {
          var a = ans[0];
          if (a) {
            var rightContent = ans[0].correct_content;
            if (inputAnswerValue == rightContent) {
              console.log("正确答案为==" + rightContent);
              exam_inputPoint += xzExamPaper.completionPoint;
            }


          }

        }

      }
    } else {
      //单选 多选 不定项
      //判断答案 计算得分
      if (!mult_answerList || mult_answerList.length == 0) {
        wx.showToast({
          title: "您还没有作答！",
          icon: "none"
        })
        return;
      }
      if (currentExamType == 0) {
        //不定项选择题
        var isRight = that.isMultExamRightAnswer(examInfo);
        if (isRight) {
          // 加分
          exam_unsurenessPoint +=xzExamPaper.unsurenessPoint;
        }

      } else if (currentExamType == 1) {
        if (mult_answerList) {
          var item = mult_answerList[0];
          if (item.correct == 1) {
            //正确 加分
            exam_singlePoint += xzExamPaper.singlePoint;
          }
        }

      } else if (currentExamType == 2) {
        if (mult_answerList.length < 2) {
          wx.showToast({
            title: "请至少选择2个答案",
            icon: "none"
          })
          return;
        }

        var isRight = that.isMultExamRightAnswer(examInfo);
        if (isRight) {
          // 加分
          exam_multpoint += xzExamPaper.multiplePoint;
        }

      } else if (currentExamType == 3) {
        if (mult_answerList) {
          var item = mult_answerList[0];
          if (item.correct == 1) {
            //正确 加分
            exam_booleanPoint += xzExamPaper.checkPoint;
          }
        }
      }



    }
    //------------得分输出 调试 --------------------
    console.log("目前不定项得分==" + exam_unsurenessPoint);
    console.log("目前单选得分==" + exam_singlePoint);
    console.log("目前多选得分==" + exam_multpoint);
    console.log("目前判断得分==" + exam_booleanPoint);
    console.log("目前填空得分==" + exam_inputPoint);

    //重置部分数据 
    mult_answerList = []; //清空用户选择的答案集合
    this.setData({ //清空填空题输入框上一题的答案
      inputAnswerValue: null
    })
    console.log("目前填空为==" + this.data.inputAnswerValue);
    // 2 作答之后开始下一题
    this.startNextQuestion();
  },

  //判断多选答案是否正确
  isMultExamRightAnswer: function (examInfo) {

    if (mult_answerList) {
      //1 数对上 2每个答案都对
      if (mult_answerList.length == examInfo.correctCount) {
        //对用户选择的答案进行遍历 如果每一个答案都是正确的 那么该道多选题就是正确的
        for (var i = 0; i < mult_answerList.length; i++) {
          var sItme = mult_answerList[i];
          if (sItme.correct != 1) {
            return false;
          }
        }
        return true;
      }
    }
    return false;

  },



  //本轮 答题结束 打开结果
  startResult: function () {

    //总分 得分
    if (singleQList != null && singleQList.length > 0) {
      examResultInfo.exam_singleTotal = xzExamPaper.singleTotalPoint;
      examResultInfo.exam_singleScore = exam_singlePoint;
    }
    if (multQList != null && multQList.length > 0) {
      examResultInfo.exam_multTotal = xzExamPaper.multipleTotalPoint;
      examResultInfo.exam_multScore = exam_multpoint;

    }
    if (booleanQList != null && booleanQList.length > 0) {
      examResultInfo.exam_booleanTotal = xzExamPaper.checkTotalPoint;
      examResultInfo.exam_booleanScore = exam_booleanPoint;
    }
    if (inputQList != null && inputQList.length > 0) {
      examResultInfo.exam_inputTotal = xzExamPaper.completionTotalPoint;
      examResultInfo.exam_inputScore = exam_inputPoint;
    }

    //不定向分数计算
    if (unsurenessQList != null && unsurenessQList.length > 0) {
      examResultInfo.exam_unsurenessTotal = xzExamPaper.unsurenessTotalPoint;
      examResultInfo.exam_unsurenessScore = exam_unsurenessPoint;//当前不定项分数
      console.log('exam_unsurenessPoint' + exam_unsurenessPoint)
    }

    //总分
    examResultInfo.exam_ScoreTotal = xzExamPaper.totalPoint;
    //本次考试总得分
    examResultInfo.exam_Score = (exam_singlePoint + exam_multpoint
      + exam_booleanPoint + exam_inputPoint + exam_unsurenessPoint);

    console.log('zongfen' + examResultInfo.exam_Score)

    //考试id
    examResultInfo.examId = xzExamPaper.examId;
    examResultInfo.examInfo = examDescInfo;
    //输出本轮答题结果
    console.log("本轮答题结果==" + JSON.stringify(examResultInfo));

    //保存到本地 打开结果页面
    try {
      wx.setStorageSync(config.examResultInfo, examResultInfo);
      wx.redirectTo({
        url: '../examLoading/examLoading?fromType=2'
      })

    } catch (e) {

    }



  }


})